#include "cs8tableview.h"

#include <QKeyEvent>
#include <QDebug>
#include <QMessageBox>
#include "spinboxdelegate.h"

cs8TableView::cs8TableView(QWidget *parent) :
    QTableView(parent)
{
    setItemDelegateForColumn (0,new SpinBoxDelegate(this,0));
    setItemDelegateForColumn (1,new SpinBoxDelegate(this,0));
    setItemDelegateForColumn (2,new SpinBoxDelegate(this,2,true));
    setItemDelegateForColumn (3,new SpinBoxDelegate(this,2,true));
    setTabKeyNavigation (true);
}

void cs8TableView::setSellerModel(QStandardItemModel *model)
{
    m_sellermodelModel=model;
}

void cs8TableView::clearSalesRows()
{
    m_salesModel->clear ();
    m_salesModel->setColumnCount (5);
    m_salesModel->setHorizontalHeaderLabels (QStringList() << trUtf8 ("Verkäufer") << trUtf8 ("Anzahl") << trUtf8 ("Einzelpreis") << trUtf8 ("Summe") << trUtf8 ("Name") );
    emit salesCleared();
            /*
             *ui->cbNewSale->setEnabled (true);
            ui->cbCancelSale->setEnabled (false);
            ui->cbCompleteSale->setEnabled (false);
            ui->tableViewSales->setEnabled (false);
            ui->toolButtonRemoveLine->setEnabled (false);
            ui->lineEditTotal->setValue (0);
            ui->cbNewSale->setFocus ();
                    */
}


void cs8TableView::removeCurrentRow()
{
    QModelIndex index=currentIndex ();
    if (index.isValid())
    {
        int row=index.row();
        if (QMessageBox::question (this,
                                   trUtf8 ("Frage"),
                                   trUtf8 ("Soll die akutelle Zeile entfernt werden?"),
                                   QMessageBox::Yes|QMessageBox::No)==QMessageBox::Yes)
        {
            model()->removeRows (row,1);
        }
    }
}

void cs8TableView::keyPressEvent(QKeyEvent *event)
{
    if (event->key ()==Qt::Key_Return)
    {
        qDebug() << "cs8TableView: Key_Return";
        QKeyEvent event(QEvent::KeyPress, Qt::Key_Tab, Qt::NoModifier);
        QTableView::keyPressEvent(&event);
    }
    else
    {
        QTableView::keyPressEvent (event);
    }
}
void cs8TableView::addEmptySalesRow()
{
    //m_salesModel->blockSignals(true);
    QStandardItemModel *model_=qobject_cast<QStandardItemModel*>(model());
    int row=model()->rowCount ();

    model_->insertRow (row);
    model_->setData (model()->index (row,4),"");
    model()->setData (model()->index (row,3),"");
    model()->setData (model()->index (row,3),Qt::AlignCenter , Qt::TextAlignmentRole);
    model()->setData (model()->index (row,2),"");
    model()->setData (model()->index (row,2),Qt::AlignCenter, Qt::TextAlignmentRole);
    model()->setData (model()->index (row,1),"");
    model()->setData (model()->index (row,1),Qt::AlignCenter, Qt::TextAlignmentRole);
    model()->setData (model()->index (row,0),"0");
    model()->blockSignals (true);
    model_->item (row,1)->setText ("1");
    model_->item (row,4)->setFlags (Qt::NoItemFlags);
    model_->item (row,3)->setFlags (Qt::NoItemFlags);
    model_->blockSignals (false);
    // m_salesModel->blockSignals(false);
}

void cs8TableView::slotItemChanged(QStandardItem *item)
{
    int row=item->row ();
    QString data=item->data (Qt::DisplayRole).toString().remove(trUtf8 ("€")).trimmed();

    if ((row==model()->rowCount ()-1) && (item!=0) && (data.toDouble ()>0))
    {
        addEmptySalesRow ();
    }

    switch (item->column ())
    {
    // seller has changed, check if it exists
    case 0:
    {
        QString seller=item->text ();
        QBrush brush;
        QList<QStandardItem *> list=m_sellermodelModel->findItems (seller,Qt::MatchExactly,0);
        if (list.count ()==0)
        {
            brush.setColor (Qt::red);
            m_salesModel->item (row,4)->setText ("");
        }
        else
        {
            brush.setColor (Qt::white);
            QString name=m_sellermodelModel->item (list.at(0)->row (),1)->text ();
            m_salesModel->item (row,4)->setText (name);
            resizeColumnToContents (4);
        }
        item->setBackground (brush);
        item->setData (brush,Qt::BackgroundRole);
        break;
    }
        // quantity or amount has changed
    case 1:
    case 2:
    {
        if (m_salesModel->item (row,1)!=0 && m_salesModel->item (row,2)!=0)
        {
            QString qty=m_salesModel->item (row,1)->text ();
            QString amount=m_salesModel->item (row,2)->text ();
            amount.chop(1);
            double sum= qty.toDouble()*amount.toDouble();
            m_salesModel->item (row,3)->setText (trUtf8 ("%1 €").arg(sum,0,'f',2));
            calculateTotalSum();
        }
        break;
    }
    }
}

void cs8TableView::calculateTotalSum()
{
    double total=0;
    for (int row=0;row<model()->rowCount ();row++)
    {
        QString data=m_salesModel->item (row,3)->text ();
        data.remove(trUtf8 ("€"));
        total += data.toDouble ();
    }
    emit totalSumChanged (total);
}


void cs8TableView::setModel(QAbstractItemModel *model)
{
    QTableView::setModel (model);
    connect(model,SIGNAL(itemChanged(QStandardItem*)),this,SLOT(slotItemChanged(QStandardItem*)));
    m_salesModel=qobject_cast<QStandardItemModel*>( model );
}

